package com.shqcjd.yunweiyanoperator.ui.activity.remote;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.orhanobut.logger.Logger;
import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.app.MyApp;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.model.eventbus.ReloginEvent;
import com.shqcjd.yunweiyanoperator.model.pojo.FileBean;
import com.shqcjd.yunweiyanoperator.ui.adapter.RemoteFileListAdapter;
import com.shqcjd.yunweiyanoperator.ui.base.BaseActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.shqcjd.yunweiyanoperator.util.UIUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.agora.IAgoraAPI;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 远程指导文件列表
 */
public class RemoteFileListActivity extends BaseActivity {

    @BindView(R.id.btn_finish)
    ImageView ivToolbarBack;
    @BindView(R.id.tv_title)
    TextView tvToolbarCenter;
    @BindView(R.id.rv_file_list)
    RecyclerView rvFileList;
    private String mChannelID = "";
    private RemoteFileListAdapter remoteFileListAdapter;
    private AgoraAPIOnlySignal mAgoraAPI;
    private Context mContext;
    private int guideOrRepair = 0;//如果是从远程指导页0进来的，没有巡检记录的视频（0）；如果是维修记录页进来的，则有巡检记录视频（1）

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_remote_file_list;
    }

    @Override
    public void initView() {
        mContext = this;
        mAgoraAPI = MyApp.the().getmAgoraAPI();
        tvToolbarCenter.setText("文件列表");
        mChannelID = getIntent().getStringExtra("channelID");
        guideOrRepair = getIntent().getIntExtra("guideOrRepair", 0);
        initAdapter();
    }
    private void initAdapter() {
        remoteFileListAdapter = new RemoteFileListAdapter();
        rvFileList.setLayoutManager(new LinearLayoutManager(this));
        rvFileList.setAdapter(remoteFileListAdapter);
        DefaultItemAnimator animator = new DefaultItemAnimator();
        rvFileList.setItemAnimator(animator);
        remoteFileListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                FileBean item = (FileBean) adapter.getItem(position);
                Intent intent = new Intent(mContext, UIUtils.previewClass(item.extension));
                intent.putExtra("name", item.fileName);
                intent.putExtra("url", item.url);
                startActivity(intent);
            }
        });
    }

    @Override
    public void initData() {
        if(guideOrRepair==0){
            initGuideFileData();
        }else{
            initFileData();
        }
    }

    private void initGuideFileData() {
        Map<String, String> map = new HashMap<>();
        map.put("roomId", mChannelID);
        ApiService.getGuideFileList(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new Observer<ResponseData<List<FileBean>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData<List<FileBean>> retData) {
                        if (retData.retCode== 10000) {
                            remoteFileListAdapter.setNewData(retData.data);
                            rvFileList.smoothScrollToPosition(remoteFileListAdapter.getItemCount()-1);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void initFileData() {
        Map<String, String> map = new HashMap<>();
        map.put("roomId", mChannelID);
        ApiService.getFileList(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new Observer<ResponseData<List<FileBean>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData<List<FileBean>> retData) {
                        if (retData.retCode== 10000) {
                            remoteFileListAdapter.setNewData(retData.data);
//                            rvFileList.smoothScrollToPosition(remoteFileListAdapter.getItemCount()-1);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        addSignalingCallback();
    }

    private void addSignalingCallback() {
        if (mAgoraAPI == null) {
            return;
        }

        mAgoraAPI.callbackSet(new AgoraAPI.CallBack() {
            @Override
            public void onLogout(final int i) {
                Logger.i("Agora onLogout:" + i);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (i == IAgoraAPI.ECODE_LOGOUT_E_KICKED) { // 账号其他地方登录
                            EventBus.getDefault().post(new ReloginEvent());
                        } else if (i == IAgoraAPI.ECODE_LOGOUT_E_NET) { // 网络问题
                            ToastUtils.showShort(mContext, "网络异常，可能无法收到对方文件！");
                        }
                    }
                });

            }

            /**
             * 收到频道消息回调
             * @param channelID 频道名
             * @param account 客户端定义的用户账号
             * @param uid 固定填 0
             * @param msg 消息正文
             */
            @Override
            public void onMessageChannelReceive(String channelID, final String account, final int uid, final String msg) {
                super.onMessageChannelReceive(channelID, account, uid, msg);
                Logger.i("接收到频道消息: account:"+account+" uid:"+uid+" msg:"+msg);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showShort(mContext,"收到新信息");
                        initFileData();
                    }
                });
            }

        });
    }

    @OnClick(R.id.btn_finish)
    public void onViewClicked() {
        finish();
    }
}
